<template>
    <div>
      <div>
        <el-tabs v-model="editableTabsValue" type="border-card" @tab-remove="removeTab">
          <el-tab-pane :closable="item.closable" v-for="(item,index) in tabPaneList" :name="item.name"  :key="index" :label="item.label">

<!--            文章列表-->
            <div v-if="item.name=='list'">
              <div>
                <el-table
                    :data="tableData"
                    stripe
                    border
                    style="width: 100%">
                  <el-table-column
                      prop="id"
                      label="ID"
                      sortable
                      width="80">
                  </el-table-column>
                  <el-table-column
                      prop="title"
                      label="标题"
                      >
                  </el-table-column>
                  <el-table-column
                      prop="cate_name"
                      label="类型"
                      sortable
                      width="80"
                      >
                  </el-table-column>
                  <el-table-column
                      label="作者"
                      width="100"
                  >
                    <template slot-scope="scope">
                      {{scope.row.username||'admin'}}
                    </template>
                  </el-table-column>
                  <el-table-column
                      label="封面图"
                      width="150">
                    <template slot-scope="scope">
                      <el-image :src="baseURL+scope.row.cover_img" :preview-src-list="[baseURL+scope.row.cover_img]"></el-image>
                    </template>
                  </el-table-column>
                  <el-table-column
                      label="参与量/阅读量/点赞量">
                    <template slot-scope="scope">
                      <span class="typeCount">{{scope.row.partq}}</span>
                      <span class="typeCount">{{scope.row.readq}}</span>
                      <span class="typeCount">{{scope.row.followq}}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                      sortable
                      prop="state"
                      label="发布状态" width="100">
                    <template slot-scope="scope">
                      <el-tag
                          :type="scope.row.state>=0?'primary':'warning'"
                          disable-transitions>{{artState(scope.row.state)}}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                      prop="pub_date"
                      label="发布时间"
                      sortable
                      width="100">
                  </el-table-column>
                  <el-table-column
                      label="是否显示"
                      width="100">
                    <template slot-scope="scope">
                      <el-switch
                          v-model="scope.row.is_show"
                          :active-value="1"
                          :inactive-value="0"
                          @change="val=>(swichEvent(val,scope.row.id))">
                      </el-switch>
                    </template>
                  </el-table-column>
                  <el-table-column
                      fixed="right"
                      label="操作">
                    <template slot-scope="scope">
                      <el-button type="primary" plain @click="updateClick(scope.row)">编辑</el-button>
                      <el-button type="danger" plain @click="deleteClick(scope.row.id)">删除</el-button>
                      <el-button type="info" plain @click="replayClick(scope.row.id)">回复</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                    layout="prev, pager, next"
                    :total="total">
                </el-pagination>
              </div>
            </div>

<!--            添加文章-->
            <div v-if="item.name=='add'">
              <el-form ref="addRuleForm"  :rules="rules" :model="addForm" label-position="right" label-width="80px">
                <el-form-item label="发布者ID" prop="author_id">
                  <el-input v-model="addForm.author_id" disabled autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                  <el-input v-model="addForm.title" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="cid">
                  <el-select v-model="addForm.cid">
                    <el-option v-for="item in artCateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="封面图" prop="cover_img">
                  <el-button style="margin-bottom: 5px" type="primary" @click="openMapClick">选择一张广告图</el-button>
                  <el-input v-model="addForm.cover_img" disabled></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                  <el-select v-model="addForm.state">
                    <el-option v-for="(item,index) in artStateList" :key="index" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="文章内容" prop="content">
                  <quill-editor
                      ref="myAddEditor"
                      class="editor-wrap"
                      v-model="addForm.content"
                      :options="editorOption"
                  >
                  </quill-editor>
                </el-form-item>
              </el-form>
              <div style="text-align: center">
                <el-button>取 消</el-button>
                <el-button type="primary" @click="addUserEvent">确 定</el-button>
              </div>
            </div>
 <!--            修改文章-->
<!--            v-if="item.name=='edit'"-->
            <div v-if="item.name=='edit'">
              <el-form ref="upRuleForm"  :rules="rules" :model="updateForm" label-position="right" label-width="80px">
                <el-form-item label="文章ID"  prop="id">
                  <el-input v-model="updateForm.id" disabled autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="发布者ID" prop="author_id">
                  <el-input v-model="updateForm.author_id" disabled autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="标题" prop="title">
                  <el-input v-model="updateForm.title" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="类型" prop="cid">
                  <el-select v-model="updateForm.cid">
                    <el-option v-for="item in artCateList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="封面图" prop="cover_img">
                  <el-button style="margin-bottom: 5px" type="primary" @click="openMapClick">选择一张广告图</el-button>
                  <el-input v-model="updateForm.cover_img" disabled></el-input>
                </el-form-item>
                <el-form-item label="状态" prop="state">
                  <el-select v-model="updateForm.state">
                    <el-option v-for="(item,index) in artStateList" :key="index" :label="item.label" :value="item.value"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="文章内容" prop="content">
                  <quill-editor
                      ref="myEditEditor"
                      class="editor-wrap"
                      v-model="updateForm.content"
                      :options="editorOption"
                  >
                  </quill-editor>
                </el-form-item>
              </el-form>
              <div style="text-align: center">
                <el-button @click="removeTab('edit')">取 消</el-button>
                <el-button type="primary" @click="updateUserEvent">确 定</el-button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <MapSelect ref="mapPop" @mapselectEvent="mapselectEvent"></MapSelect>
      <MapSelect ref="artPop" @mapselectEvent="artselectEvent"></MapSelect>
    </div>
</template>

<script>
import { quillEditor,Quill } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";


import { ImageDrop } from "quill-image-drop-module";
import ImageResize from "quill-image-resize-module";
Quill.register("modules/imageDrop", ImageDrop);
Quill.register("modules/imageResize", ImageResize);

import {addArticleList, deleBanner, editArticleList, getArticleCate, getArticleList} from '@/request'
import MapSelect from "@/components/MapSelect";
import menu from '@/assets/menu.json'
export default {
  name: "List",
  components:{
    MapSelect,
    quillEditor
  },
  data(){
    return {
      editorOption: {
        placeholder: '请输入文章内容...',
        modules: {
          toolbar:{
            container: [
              [{ 'color': [] }, { 'background': [] }],
              ['bold', 'italic', 'underline', 'strike'],
              [{'size': ['small', false, 'large']}],
              [{'list': 'ordered'}, {'list': 'bullet'}],
              ['link', 'image'],
              [{ 'align': [] }],
            ],
            handlers:{
              image: (val)=>{
                if(val){
                  this.$refs.artPop.showMapSelect()
                }else{
                  this.quill.format('image', false)
                }
              }
            }
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"],
          },
        }
      },
      artStateList:menu.artStateList,
      editableTabsValue:"list",
      tableData:[],
      artCateList:[],
      pagenum:0,
      total:0,
      formSearch:{
        cid:null,
        title:null,
        author_id:null,
      },
      tabPaneList:[
        {
          label:"文章列表",
          name:"list",
          closable:false
        },
        {
          label:"添加文章",
          name:"add",
          closable:false,
        }
      ],
      updateForm:{},
      addForm:{
        author_id:this.$store.state.token.adminid,
        title:null,
        cid:null,
        cover_img:null,
        state:null,
        content:null
      },
      rules:{
        title: [
          {required: true, message: '请输入文章描述', trigger: 'blur'  },
        ],
        cid: [
          {required: true, message: '请选择文章类型', trigger: 'blur'  },
        ],
        cover_img: [
          {required: true, message: '请选择文章封面图', trigger: 'blur'  },
        ],
        state: [
          {required: true, message: '请选择文章的发布状态', trigger: 'blur'  },
        ]
      }
    }
  },
  computed:{
    artState(){
      return function (value){
        let active=this.artStateList.find(o=>o.value==value)
        return active.label
      }
    }
  },
  created() {
    this.getarticleCate();
    this.getarticleList();
  },
  methods:{
    async getarticleCate(){
      let data=await getArticleCate({is_dele:0});
      if(data.code!=200)return this.$message.error(data.message);
      this.artCateList=data.data;
    },
    async getarticleList(){
      if(this.pagenum*10>this.total)return;
      this.pagenum++;
      this.formSearch['pagenum']=this.pagenum;
      this.formSearch['is_delete']=0;
      let data=await getArticleList(this.formSearch)
      if(data.code!=200)return this.$message.error(data.message);
      this.tableData=data.data.list;
      this.total=data.data.total;
    },
    addTab() {
      this.removeTab('edit');
      this.tabPaneList.push({
        label:"编辑文章",
        name:"edit",
        closable:true,
      });
      this.editableTabsValue = 'edit';
    },
    removeTab(targetName) {
      let tabs = this.tabPaneList;
      let activeName = this.editableTabsValue; //获取当前选中
      if (activeName === targetName) { //关闭=选中
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1]; //前后或后面
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
      }
      this.editableTabsValue = activeName;
      this.tabPaneList = tabs.filter(tab => tab.name !== targetName);
    },
    async swichEvent(val,id){
      let data=await editArticleList({id,is_show:val});
      if(data.code!=200)return this.$message.error(data.message);
      this.$message.success(data.message);
      this.getarticleList();
    },
    updateClick(item){
      this.updateForm={
        id:item.id,
        cid:item.cid,
        title:item.title,
        content:item.content,
        cover_img:item.cover_img,
        state:item.state,
        author_id:item.author_id
      };
      this.addTab()
    },
    openMapClick(){
      this.$refs.mapPop.showMapSelect()
    },
    mapselectEvent(value){
      if(this.editableTabsValue=='add')this.addForm['cover_img']=value.length&&value[0].filepath
      if(this.editableTabsValue=='edit')this.updateForm['cover_img']=value.length&&value[0].filepath
    },
    artselectEvent(value){
      let quill=null;
      if(this.editableTabsValue=='add')quill=this.$refs.myAddEditor[0].quill;
      if(this.editableTabsValue=='edit')quill=this.$refs.myEditEditor[0].quill;

      //获取光标所在位置
      let length=quill.selection.savedRange.index;
      //插入图片
      quill.insertEmbed(length,'image',this.baseURL+value[0].filepath);
      quill.setSelection(length+1);
    },
    async updateUserEvent(){
      let that=this;
      this.$refs['upRuleForm'][0].validate(async (valid)=>{
        if(!valid){
          return false;
        }
        let data=await editArticleList(this.updateForm);
        if(data.code!=200)return this.$message.error(data.message);
        this.$message.success(data.message);
        this.init();
        this.getarticleList();
      })
    },
    init(){
      this.pagenum=0
      this.total=0
    },
    addUserEvent(){
      let that=this;
      this.$refs['addRuleForm'][0].validate(async (valid)=>{
        if(!valid){
          return false;
        }
        let data=await addArticleList(that.addForm);
        if(data.code!=200)return this.$message.error(data.message);
        this.$message.success('添加成功!');
        this.init();
        this.getarticleList();
        this.addForm={
          author_id:this.$store.state.token.adminid,
              title:null,
              cid:null,
              cover_img:null,
              state:null,
              content:null
        }
      })
    },
    replayClick(id){
      this.$router.push({name:'Replay',params:{id}})
    },
    deleteClick(id){
      this.$confirm('您将删除该文章, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data=await editArticleList({id,is_delete:1});
        if(data.code!=200)return this.$message.error(data.message);
        this.$message.success(data.message);
        this.init();
        this.getarticleList();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
  }
}
</script>

<style lang="scss" scoped>
 .typeCount{
  margin: 0px 5px;
}

 /deep/ .editor-wrap .ql-container{
   min-height: 300px;
 }
</style>